package in.rinisoft.sonar.maven.plugin;

import java.io.IOException;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MavenPluginManager;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;

/**
 * Goal which executes sonar analysis
 * 
 * @goal sonar
 * @aggregator
 * 
 * @note Code has been taken from Codehaus Sonar plugin and modified to suit the
 *       needed whereever needed
 * @author Neeraj Mittal 
 */
public class SonarMojo extends AbstractMojo {
	/**
	 * @parameter expression="${project}"
	 * @required
	 * @readonly
	 */
	protected MavenProject project;

	/**
	 * @parameter expression="${session}"
	 * @required
	 * @readonly
	 */
	private MavenSession session;

	/**
	 * Sonar host URL
	 * 
	 * @parameter expression="${sonar.host.url}"
	 *            default-value="http://localhost:9000" alias="sonar.host.url"
	 * 
	 */
	private String sonarHostURL;

	/**
	 * @component
	 * @required
	 */
	protected MavenPluginManager mavenPluginManager;

	/**
	 * The artifact repository to use.
	 * 
	 * @parameter expression="${localRepository}"
	 * @required
	 * @readonly
	 */
	protected ArtifactRepository localRepository;

	public void execute() throws MojoExecutionException, MojoFailureException {
		try {
			ServerMetadata server = new ServerMetadata(sonarHostURL);
			server.logSettings(getLog());

			if (server.supportsMaven3()) {
				new Bootstraper(mavenPluginManager).start(project, session);
			} else {
				throw new MojoExecutionException("Sonar " + server.getVersion()
						+ " does not support Maven 3");
			}
		} catch (IOException e) {
			throw new MojoExecutionException("Failed to execute Sonar", e);
		}
	}
}